package com.example.ex8

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.ex8.databinding.ActivityMain2Binding
import com.example.ex8.weather.Forecast
import com.example.ex8.weather.Weather
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class MainActivity2 : AppCompatActivity() {
    val baseURL ="http://t.weather.itboy.net/api/weather/city/"
    override fun onCreate(savedInstanceState: Bundle?) {
        val binding = ActivityMain2Binding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        val cityCode = intent.getStringExtra("city_code")
        val queue = Volley.newRequestQueue(this)
        val stringRequest = StringRequest(baseURL + cityCode, {
            val gson = Gson()
            val WeatherType=object: TypeToken<Weather>(){}.type
            val weather = gson.fromJson<Weather>(it, WeatherType)
            binding.textViewCity.text = weather.cityInfo.city
            binding.textViewProvince.text = weather.cityInfo.parent
            binding.textViewShidu.text = weather.data.shidu
            binding.textViewWendu.text = weather.data.wendu
            val firstDay = weather.data.forecast.first()
            when(firstDay.type){
                "晴"-> binding.imageView.setImageResource(R.drawable.sun)
                 "多云"-> binding.imageView.setImageResource(R.drawable.cloud)
                 "阴"-> binding.imageView.setImageResource(R.drawable.cloud)
                 "雨"-> binding.imageView.setImageResource(R.drawable.rain)
                 "雪"-> binding.imageView.setImageResource(R.drawable.snow)
                else-> binding.imageView.setImageResource(R.drawable.thunder)
            }
            val adapter = ArrayAdapter<Forecast>(this, android.R.layout.simple_list_item_1, weather.data.forecast)
            binding.listView.adapter = adapter

            Log.d("MainActivity2", "${weather.cityInfo.city} ${weather.cityInfo.parent}")
        },{
            Log.d("MainActivity2", "$it")
        })
        queue.add(stringRequest)
    }
}